<template>
  <span>
    <el-button icon="el-icon-upload" type="success" size="medium" @click="handleOpen">导入</el-button>
    <div style="display: none">
      <ele-import
        :fields="fields"
        :filepath="filepath"
        :request-fn="requestFn"
        :rules="rules"
        :tips="tips"
        :formatter="formatter"
        :title="title"
        :visible.sync="visible"
        @close="handleCloseImport"
        @finish="handleFinishImport"
      />
    </div>
  </span>
</template>

<script>
import EleImport from 'vue-ele-import'
export default {
  name: 'App',
  components: {
    EleImport
  },
  data() {
    return {
      // 弹窗的标题
      title: '导入模板',
      // 提示信息
      tips: ['请下载后将修改的内容复制到模板中再上传，系统根据ID来修改，不会新建，请勿修改id'],
      // 假如数据库中是`name`字段, 而Excel模板列是`名字`, 就需要写成 name: '名字'
      // ele-import 内部会抛弃非定义在fields里的列
      fields: {
        id: 'id',
        product: '产品',
        name: '规格',
        price: '售价',
        marketPrice: '市场价'
      },
      formatter: {
      },
      rules: {
        id: { type: 'number', required: true, message: 'id不能为空' },
        price: { type: 'number', required: true, message: '价格不能为空' }
      },
      filepath: `https://wechat.jmgc.vip/import.xlsx`,
      // 控制弹窗, 和dialog的visible一样
      // https://element.eleme.cn/#/zh-CN/component/dialog
      visible: false
    }
  },
  mounted() {
    console.log('route', window.location.host)
  },
  methods: {
    // requestFn函数会被注入请求的数据
    // 需要返回一个Promise对象
    async requestFn(data) {
      console.log(data)
      const specifications = []
      for (const i of data) {
        const children = {
          id: i.id,
          price: i.price,
          macketPrice: i.macketPrice
        }
        specifications.push(children)
      }
      this.axios.post(`/manage/specifications/batch-update`, specifications, { params: {
        '@basis': 'id',
        '@mode': 'update'
      }}).then((res) => {
        location.reload
      })
    },
    handleCloseImport() {
      console.log('组件关闭了~')
    },
    handleFinishImport() {
      console.log('导入完毕了~')
      location.reload()
    },
    handleOpen() {
      this.visible = true
    }
  }
}
</script>

<style scoped>

</style>
